//引入微信配置
const wx = require('../config/wx');

//引入日志
const {
    logger
} = require('../config/logger');

//处理node request请求
const request = require('request');

//定义存储accessToken
const accessTokenJson = {
    access_token: "",
    expires_time: ""
};

const accessToken = {
    //获取wx accessToken
    getAccessToken: () => {
        return new Promise((resolve, reject) => {
            const appid = wx.appid;
            const secret = wx.secret;
            let options = {
                method: 'GET',
                url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`,
            };
            //获取当前时间
            const currentTime = new Date().getDate();
            if (accessTokenJson.access_token == "" || accessTokenJson.expires_time < currentTime) {
                request(options, (error, response, body) => {
                    if (error) {
                        reject(error);
                        logger().error("获取accessToken失败: " + error);
                    } else {
                        //返回值的字符串转JSON
                        let _data = JSON.parse(body);
                        accessTokenJson.access_token = _data.access_token;
                        accessTokenJson.expires_time = new Date().getTime() + (parseInt(_data.xpires_in) - 200) * 1000;
                        resolve(accessTokenJson.access_token);
                    }
                })
            } else {
                resolve(accessTokenJson.access_token);
            }
        })
    }
}

//执行主函数
accessToken.getAccessToken();


module.exports = accessToken;